'use strict';
const jwt = require('jsonwebtoken');

module.exports = (options, app) => {
  return async ctx => {
    const accessToken = ctx.header['access-token'];
    if (accessToken) {
      const token = accessToken.split(' ')[1];
      try {
        const decoded = jwt.verify(token, options.jwt.secret);
        const { id } = decoded;
        const data = await app.redis.get(id);
        const user = JSON.parse(data);
        ctx.user = user;
      } catch (error) {
        ctx.throw(401);
      }
      return;
    }
    ctx.throw(401);
  };
};
